package com.techfort.metalrss.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.techfort.metalrss.core.Feed;

public class FavouriteProvider {
	
	private Context context;
	private FavouritesHelper helper;
	private SQLiteDatabase db;
	private static final String TABLE = "feeds";
	private String [] columns = new String [] {"id","feed_name","lang_id","link"};
	private Cursor cur;
	
	public FavouriteProvider(Context context){
		this.context = context;
	}
	
	public FavouriteProvider open(){
		helper = new FavouritesHelper(context);
		db = helper.getWritableDatabase();
		return this;
	}
	
	public void insert(Feed feed){
		db.execSQL("INSERT INTO " + TABLE + " values (" + feed.getId() + ", '" + feed.getFeed_name() + "','" + feed.getLang_id() + "','" + feed.getLink() + "')");
	}
	
	public void delete(Feed feed){
		db.execSQL("DELETE FROM " + TABLE + " where id=" + feed.getId());
	}
	
	public Feed select(Feed feed){
		
		cur = db.query(TABLE, columns ,"id=?", new String [] {Integer.toString(feed.getId())} , null, null, null );
		
		cur.moveToFirst();
		return Feed.readFromCursor(cur);
	}
	
	public List<Feed> getAll(){
		List<Feed> feeds = new ArrayList<Feed>();
		cur = db.query(TABLE, columns, null, null, null, null, null);
		cur.moveToFirst();
		while(cur.isAfterLast()==false){
			feeds.add(Feed.readFromCursor(cur));
			cur.moveToNext();
		}
		return feeds;
	}
	
	
	public void close(){
		if(cur!=null) cur.close();
		db.close();
	}
	
	
}
